package ali;

import java.util.Random;

import static java.lang.Thread.sleep;

/**
 * @author keboom
 * @date 2021/4/29 14:11
 */
public class TransferMoney implements Runnable {

    @Override
    public void run() {
        int transferSuccessNum = 1;
        Random random = new Random();
        while (transferSuccessNum <= 100){
            // 两个账户的后面的数字
            int a = 0, b = 0;
            while (a != b) {
                a = random.nextInt(20);
                b = random.nextInt(20);
            }

            Account account1 = (Account) Test.accountMap.get("account" + a);
            Account account2 = (Account) Test.accountMap.get("account" + b);
            // 随机金额
            int amount = random.nextInt(100) + 1;
            synchronized (account1) {
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (account2) {
                    if (amount <= account1.getBalance() && amount <= account2.getBalance()) {
                        account1.setBalance(account1.getBalance() - amount);
                        account2.setBalance(account2.getBalance() + amount);
                        transferSuccessNum++;
                    } else {
                        System.out.println("转账失败！");
                    }
                }

            }

        }
    }
}
